import os
import re

import requests


class WxDayEnglishVideo(object):
    def __init__(self, _root):
        self.root = _root
        self.headers = {
            'Accept': '*/*',
            'Connection': 'keep-alive',
            'Accept-Encoding': 'gzip, deflate',
            'Host': 'mp.weixin.qq.com',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1301.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 WindowsWechat'
        }

    def get_music(self,resource,name):
        music_url="https://res.wx.qq.com/voice/getvoice?mediaid=%s"%resource;
        print("music_url：" + music_url)
        path = self.root + name + "." + 'mp3'
        if not os.path.exists(self.root):
            os.mkdir(self.root)
        if not os.path.exists(path):
            res=requests.get(music_url, self.headers, verify=False)
            with open(path, 'wb') as f:
                f.write(res.content)
                f.flush()
            f.close()

    def get_url(self,url,name):
        sees=requests.Session();
        res = sees.get(url, headers=self.headers,verify=False);
        url_pattern=r'voice_encode_fileid="(.*?)"';
        url=re.findall(url_pattern,res.content.decode("utf-8"),re.I|re.S);
        try:
          print("url："+url[0])
          self.get_music(url[0],name)
        except:
            print("发生异常")


if __name__ == '__main__':
    root = "I:\\学习\\微信公众号\\每日学英语\\音频\\";
    wxMps = WxDayEnglishVideo(root)

    wxMps.get_url("http://mp.weixin.qq.com/s?__biz=MjM5MTAwNDkwMA==&amp;mid=2654010632&amp;idx=4&amp;sn=3ac8fa2b7929e74617b2704cf895da9a&amp;chksm=bd787c838a0ff595127ff54570a71fd9d0b807a78ad4c9916e806bf3bb22c0de22a9246c7ece&amp;scene=27#wechat_redirect",
                  "Hayley教口语，“刀子嘴”用英语怎么说？")



